import axios from 'axios'
import qs from 'qs'
import { BASE_URL, NOT_HAS_BASE } from './config'

axios.defaults.timeout = 60000;                        //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';        //配置请求头
// axios.defaults.baseURL = '';
axios.defaults.baseURL = BASE_URL
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
    // //在发送请求之前做某件事
    // if(config.method  === 'post'){
    //     config.data = qs.stringify(config.data);
    // }
    // config.headers.Authorization = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ7XCJsb2dpblR5cGVcIjowLFwicGFzc3dvcmRcIjpcIjEyMzQ1NlwiLFwicGhvbmVcIjpcIjE1MTY2MDI0NzY1XCIsXCJ1dWlkXCI6XCJcIn0iLCJhdXRoIjoidG9rZW4tbWQ1OjE2MDI1NTcwNDE5NTg4NTA1NjAiLCJqdGkiOiI4NjJmYWQwMzI4Njg0ZWJkOGY0ZjY4NzYyZGM0ODViNSJ9.30XZ7p7EgHjpyyOcHKPpAUsKnUWnx3S3w-xq0Ym7xdt4DufTw0KwulJQ9KrzwkGGZ2SbsS7x5x64N4ySAtiwdA"//获取token值
    return config;
},(error) =>{
    // console.log('错误的传参')
    return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
    //对响应数据做些事
    if(!res.data.success){
        return Promise.resolve(res.data);
    }
    return res;
}, (error) => {
    // console.log('网络异常')
    return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}
////返回一个Promise(发送get请求)
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params})
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

export default {
    post,
    get,
}